package com.example.touristassist;

import java.util.ArrayList;

import com.example.touristassist.DBMetadata.ColumnMetadata;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class DBTable extends SQLiteOpenHelper {
	private DBMetadata meta = new DBMetadata();
	private String name;
	private String[] columns;
	private String create_table_sql;
	
	public String getName() { return name; }
    
	public String[] getColumns() {
		if (columns == null) {
			ArrayList<String> cols = new ArrayList<String>();
			
			for(ColumnMetadata c : meta.getTables().get(this.getName()).Columns)
				cols.add(c.Name);
			
			this.columns = (String[])cols.toArray();
		}
		
		return this.columns;
    }
	
	public DBTable(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
		
		this.name = name;
		StringBuilder sb = new StringBuilder();
		sb.append("create table ");
		sb.append(meta.getTables().get(this.getName()).Name);
		sb.append(" (");
		this.create_table_sql = sb.toString();
		
		for(ColumnMetadata column : meta.getTables().get(this.getName()).Columns){
			if (!sb.toString().equals(this.create_table_sql))
				sb.append(",");
			
			sb.append(column.Name);
			sb.append(" ");
			sb.append(column.Type);
			sb.append(" ");
			sb.append(column.Arguments);
		}
		sb.append(");");
		
		this.create_table_sql = sb.toString();
	}
	
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(create_table_sql);
	}
	
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + meta.getTables().get(this.getName()).Name);
    	onCreate(db);
	}
}
